<!--
 * @Author: xuman
 * @Date: 2020-06-04 15:57:50
 * @LastEditors: xuman
 * @LastEditTime: 2020-06-15 18:42:59
-->
<template>
  <div class="page">
    <ModelSearchBar
      :searchForm.sync="searchForm"
      :options="options"
      :getList="getReportData"
    />
    <el-table
      :data="psi_table.tableData"
      v-loading="loading"
      :summary-method="getSummaries"
      show-summary
    >
      <el-table-column prop="range" label="评分区间" width="180">
      </el-table-column>
      <el-table-column label="基准时点">
        <el-table-column prop="benchmark_count" label="笔数"></el-table-column>
        <el-table-column
          prop="benchmark_ratio"
          label="基准值百分比(%)"
        ></el-table-column>
      </el-table-column>
      <el-table-column
        v-for="(item, index) in psi_table.headers"
        :key="index"
        :label="item.title"
      >
        <el-table-column
          v-for="(val, index1) in item.headers"
          :key="index1"
          :prop="val.key"
          :label="val.title"
        />
      </el-table-column>
    </el-table>

    <el-table
      :data="ks_table.tableData"
      v-loading="loading"
      :summary-method="getSummaries"
      show-summary
    >
      <el-table-column prop="model_name" label="模型名称" width="180">
      </el-table-column>
      <el-table-column label="基准时点">
        <el-table-column prop="benchmark_ks" label="K-S值"></el-table-column>
      </el-table-column>
      <el-table-column
        v-for="(item, index) in ks_table.headers"
        :key="index"
        :label="item.title"
      >
        <el-table-column
          v-for="(val, index1) in item.headers"
          :key="index1"
          :prop="val.key"
          :label="val.title"
        />
      </el-table-column>
    </el-table>

    <div class="line">
      <div id="PSI"></div>
      <div id="KS"></div>
    </div>
  </div>
</template>
<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator'
import ModelSearchBar from '../components/ModelSearchBar.vue'
import * as Api from '@/api/risksystem/xmCustomizeReport/modelReport'
import { parseTime } from '@/utils'
import LineChart from '../components/modelLine'

interface IOption {
  label: string
  value: string
}

const secondHeaderList = {
  count: '笔数',
  ratio: '百分比(%)',
  psi: 'PSI',
  ks: 'K-S值',
  ks_difference_rate: '差异率'
}

interface ISecondHeaderList {
  count: string
  ratio: string
  psi: string
  ks: string
  ks_difference_rate: string
}

// 构造table表头 数据
const getFormatData = (
  data: any[],
  type: number,
  basicField: string,
  headerField: string[]
) => {
  // headers
  const dateList = [...new Set(data.map(item => item.date))]
    .sort((a: string, b: string) => {
      return new Date(a).getTime() - new Date(b).getTime()
    })
    .map(item => {
      const end_date = parseTime(
        new Date(new Date(item).getTime() + 6 * 24 * 60 * 60 * 1000),
        '{y}-{m}-{d}'
      )
      const obj = {
        date: item,
        dateRange: `${item} - ${end_date}`
      }
      return obj
    })
  const headers = dateList.map(item => {
    const headers = headerField.map(val => ({
      key: `${item.date}-${val}`,
      title: secondHeaderList[val as keyof ISecondHeaderList]
    }))
    return { title: type === 1 ? item.dateRange : item.date, headers }
  })
  // tableData
  const tempObj: any = {}
  data.forEach(item => {
    headerField.forEach(val => {
      item[`${item.date}-${val}`] = item[val]
    })
    const tempKey = item[basicField]
    if (!tempObj[tempKey]) {
      tempObj[tempKey] = item
    } else {
      tempObj[tempKey] = { ...tempObj[tempKey], ...item }
    }
  })
  const tableData = Object.values(tempObj)
  return {
    headers,
    tableData
  }
}

@Component({
  components: {
    ModelSearchBar
  }
})
export default class ModelStability extends Vue {
  private options: any = {}
  private searchForm: any = {
    unit_type: 1
  }
  private psi_table: any = {}
  private ks_table: any = {}
  private loading: boolean = false

  private async getReportData() {
    this.loading = true
    const { unit_type } = this.searchForm
    try {
      const {
        data: { psi_report, ks_report, psi_line, ks_line }
      } = await Api.getStabilityReportData(this.searchForm)
      this.psi_table = getFormatData(psi_report, unit_type, 'range', [
        'count',
        'ratio',
        'psi'
      ])
      this.ks_table = getFormatData(ks_report, unit_type, 'model_name', [
        'ks',
        'ks_difference_rate'
      ])
      const tempObj: any = { PSI: psi_line, KS: ks_line }
      for (let key in tempObj) {
        const LineChartReport = new LineChart(key)
        LineChartReport.setOption(tempObj[key])
      }
    } finally {
      this.loading = false
    }
  }

  async created() {
    await this.getSelectOptions()
    this.getReportData()
  }

  private async getSelectOptions() {
    const obj = {
      type: ['overall_stability']
    }
    const {
      data: { overall_stability }
    } = await Api.getSelectOptions(obj)
    this.options = overall_stability
  }

  // 合计
  private getSummaries(param: any) {
    const { columns, data } = param
    const sums: any[] = []
    columns.forEach((column: any, index: number) => {
      if (index === 0) {
        sums[index] = '合计'
        return
      }
      const values = data.map((item: any) => Number(item[column.property]))
      if (!values.every((value: number) => isNaN(value))) {
        sums[index] = values.reduce((prev: number, curr: number) => {
          const value = Number(curr)
          if (!isNaN(value)) {
            return prev + curr
          } else {
            return prev
          }
        }, 0)
      } else {
        sums[index] = '-'
      }
    })
    return sums
  }
}
</script>
<style lang="scss" scoped>
.page {
  padding: 20px;
  ::v-deep .el-table {
    margin-bottom: 35px;
  }
  #PSI,
  #KS {
    width: 100%;
    height: 500px;
    margin-bottom: 35px;
  }
}
</style>
